#pip install pandas fastapi asyncpg

import asyncpg
 
async def create_pool():
    return await asyncpg.create_pool(
        database='your_database',
        user='your_username',
        password='your_password',
        host='your_host',
        port=5432  # 默认PostgreSQL端口，根据实际情况修改
    )

import pandas as pd
import asyncio
from fastapi import FastAPI
 
app = FastAPI()
pool = None  # 这将在应用启动时初始化
 
async def init_db():
    global pool
    pool = await create_pool()
 
@app.on_event("startup")
async def startup_event():
    await init_db()
 
@app.on_event("shutdown")
async def shutdown_event():
    await pool.close()
 
async def to_sql_wrapper(df, name, con, **kwargs):
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(None, df.to_sql, name=name, con=con, **kwargs)
 
@app.post("/insert_dataframe/")
async def insert_dataframe(dataframe: pd.DataFrame):
    df = dataframe.copy()  # 确保不修改传入的DataFrame
    await to_sql_wrapper(df, name='your_table', con=pool, if_exists='append', index=False)
    return {"message": "Data inserted successfully"}    


async def insert_data(df):
    async with pool.acquire() as conn:
        async with conn.transaction():
            for index, row in df.iterrows():
                await conn.execute("INSERT INTO your_table (column1, column2) VALUES ($1, $2)", row['column1'], row['column2'])    